package com.backend.common.security;

import com.backend.common.enums.UserType;
import com.backend.modules.system.entity.SysUser;
import lombok.Data;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;

import java.util.Collections;
import java.util.List;

@Data
public class AuthContext {
    private Long userId;
    private String username;
    private UserType userType;
    private List<SimpleGrantedAuthority> authorities;
    
    public static AuthContext build(SysUser user) {
        AuthContext context = new AuthContext();
        context.setUserId(user.getId());
        context.setUsername(user.getUsername());
        context.setUserType(UserType.valueOf(user.getUserType()));
        context.setAuthorities(Collections.singletonList(
                new SimpleGrantedAuthority("ROLE_" + context.getUserType().name())
        ));
        return context;
    }
    
    public static AuthContext getCurrentContext() {
        Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        if (principal instanceof AuthContext) {
            return (AuthContext) principal;
        }
        return null;
    }
} 